﻿using System.DirectoryServices.ActiveDirectory;
using Quartz.Util;
using Simple.Services.System;


namespace Simple.Services;

public class QHSEHavStandardService
{
    private readonly SimpleDbContext _context;
    private readonly IQhseFileService _qhseFileService;

    public QHSEHavStandardService(SimpleDbContext context,IQhseFileService qhseFileService)
    {
        _context = context;
        _qhseFileService = qhseFileService;
    }

    public async Task<List<QHSEHavStandardModel>> GetAsync()
    {
        var havStandards = await _context.Set<QHSESysHavStandard>().ToListAsync();
        return MapperHelper.Map<List<QHSEHavStandardModel>>(havStandards);
    }

    public async Task<PageResultModel<QHSEHavStandardModel>> GetPageAsync(PageInputModel input)
    {
        var result = new PageResultModel<QHSEHavStandardModel>();
        var query = _context.Set<QHSESysHavStandard>()
            .AsNoTracking()
             .Join(_context.Set<QHSESysDictionary>(), // Join with QHSEOrganization table
                         standard => standard.StandardCode,
                         dictionary => dictionary.Code,
                         (standard, dictionary) => new { Standard = standard, Dictionary = dictionary })
            .AsQueryable();

        // 根据条件查询
        if (!string.IsNullOrEmpty(input.Code))
        {
            query = query.Where(p => EF.Functions.Like(p.Standard.StandardCode, $"%{input.Code}%"));
        }
        if (!string.IsNullOrEmpty(input.Name))
        {
            query = query.Where(p => EF.Functions.Like(p.Standard.FileName, $"%{input.Name}%"));
        }

        // 获取总数量
        result.TotalRows = await query.CountAsync();

        // 分页查询
        query = query.OrderBy(p => p.Standard.Note).Page(input.PageNo, input.PageSize);
        var havStandards = await query.Select(u=>new QHSESysHavStandard
        {
            Id = u.Standard.Id,
            StandardCode = u.Dictionary.Item,
            FileName = u.Standard.FileName,
            FileUrl = u.Standard.FileUrl
        }).ToListAsync();
        
         var models= MapperHelper.Map<List<QHSEHavStandardModel>>(havStandards);
        result.Rows = models;
        result.SetPage(input);
        result.CountTotalPage();

        return result;
    }

    public async Task<int> AddAsync(QHSEHavStandardModel model)
    {
        if (model.File!=null)
        {
            var msg = await utilService.UploadFilesAsync(model.File, model.FileName, _qhseFileService);
            if (msg.FileStatus == 1)
            {
                model.FileUrl = "STANDARD"+model.FileName + ".pdf";
            }
        }
        var havStandard = MapperHelper.Map<QHSESysHavStandard>(model);
        await _context.AddAsync(havStandard);

        return await _context.SaveChangesAsync();
    }

    public async Task<int> UpdateAsync(QHSEHavStandardModel model)
    {
        var havStandard = await _context.Set<QHSESysHavStandard>()
           .Where(a => model.Id == a.Id)
           .FirstOrDefaultAsync();

        if (havStandard == null)
        {
            throw AppResultException.Status404NotFound("找不到标准，更新失败");
        }
        if (!string.IsNullOrEmpty(havStandard.FileUrl))
        {
                //删除这个文件
                await  _qhseFileService.RemoveAsync("ssew", havStandard.FileUrl);
        }
        if (model.File!= null)
        {
            var msg = await utilService.UploadFilesAsync(model.File, model.FileName, _qhseFileService);
            bool uploadSuccess = msg.FileStatus == 1;

            if (uploadSuccess)
            {
                model.FileUrl = "STANDARD" + model.FileName+".pdf";
            }
        }
        else
        {
            model.FileUrl = "";
        }

        MapperHelper.Map<QHSEHavStandardModel, QHSESysHavStandard>(model, havStandard);
        _context.Update(havStandard);
        int ret = await _context.SaveChangesAsync();

        if (ret == 0)
        {
            throw AppResultException.Status200OK("更新记录数为0");
        }

        return ret;
    }

    public async Task<int> DeleteAsync(IEnumerable<string> ids)
    {
        var havStandards = await _context.Set<QHSESysHavStandard>()
            .Where(p => ids.Contains(p.Id))
            .ToListAsync();
        foreach(var  havStandard in havStandards)
        {
            //删除这个文件
            await _qhseFileService.RemoveAsync("ssew",havStandard.FileUrl);
        }
        _context.RemoveRange(havStandards);
        return await _context.SaveChangesAsync();
    }
    public async Task<byte[]> DownloadPdf(IdInputModel idInputModel)
    {
        var havStandard = await _context.Set<QHSESysHavStandard>()
            .AsNoTracking()
            .Where(p => idInputModel.Id==p.Id)
            .FirstOrDefaultAsync();
        if (havStandard == null || string.IsNullOrEmpty(havStandard.FileUrl))
        {
            return null;
        }
        // 使用 IQhseFileService 接口获取文件内容
        MemoryStream stream = new MemoryStream();
        Console.WriteLine(havStandard.FileUrl);
        await _qhseFileService.GetAsync(stream, "ssew", havStandard.FileUrl);
        byte[] fileBytes = stream.ToArray();
        return fileBytes;
    }
    public async Task<byte[]> PreviewPdf(IdInputModel idInputModel)
    {
        var havStandard = await _context.Set<QHSESysHavStandard>()
            .AsNoTracking()
            .Where(p => idInputModel.Id == p.Id)
            .FirstOrDefaultAsync();
        if (havStandard == null || string.IsNullOrEmpty(havStandard.FileUrl))
        {
            return null;
        }
        Console.WriteLine(havStandard.FileUrl);
        var stream = new MemoryStream();
        await _qhseFileService.GetAsync(stream, "ssew", havStandard.FileUrl);
        byte[] fileBytes = stream.ToArray();
        return fileBytes;
    }
}
